import { getToken, setToken, removeToken } from '../../utils/auth'
import { getInfoApi, loginApi } from '@/api/user'
const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  // 设置用户资料
  setUserInfo(state, data) {
    state.userInfo = data
  },
  // 删除用户资料
  removeUserInfo() {
    state.userInfo = {}
  }
}
const actions = {
  // 登录的action
  async loginAction(context, data) {
    const res = await loginApi(data)
    console.log(res)
    context.commit('setToken', res)
  },
  // 获取用户资料的action
  async getUserProfileAction(context) {
    const res = await getInfoApi()
    console.log(res)
    context.commit('setUserInfo', res)
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }
}
export default {
  namespaced: true, // 开启命名空间
  state,
  mutations,
  actions
}
